package com.i.picgateway.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.jwt.JWTPayload;
import com.i.piccommon.exception.BusinessException;
import com.i.piccommon.util.JWTUtils;
import com.i.picgateway.config.AuthProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/10/23
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        if(isExclude(path.toString())) {
            return chain.filter(exchange);
        }
        String token = null;
        List<String> headers = request.getHeaders().get("token");
        if(!CollUtil.isEmpty(headers)) {
            token = headers.get(0);
        }
        Long userId = null;
       try {
           userId = Long.valueOf(JWTUtils.parseToken(token).getClaim("userId").toString());
       }catch (Exception exception) {
           ServerHttpResponse response = exchange.getResponse();
           response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();
       }
       String userIdString = userId.toString();
        ServerWebExchange webExchange = exchange.mutate()
                .request(builder -> builder.header("user", userIdString))
                .build();
        return chain.filter(webExchange);
    }

    private boolean isExclude(String path) {
        List<String> collect = authProperties.getExcludePaths()
                .stream()
                .filter(excludePath -> antPathMatcher.match(excludePath, path)).collect(Collectors.toList());
        return CollUtil.isNotEmpty(collect);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
